//
//  HRTabBar.m
//  网易彩票
//
//  Created by rui on 6/30/15.
//  Copyright © 2015 loverforevercyr. All rights reserved.
//

#import "HRTabBar.h"
#import "HRTabBarButton.h"



@interface HRTabBar ()
/** 用于存储创建的UIButton控件对象的NSArray */
@property(strong, nonatomic) NSMutableArray       *buttonsArray;

/**
 *  选中按钮的索引
 */
@property(assign, nonatomic) NSInteger          selectedButtonIndex;

@end

@implementation HRTabBar

#pragma mark - 懒加载

- (NSMutableArray *)buttonsArray {
    if (!_buttonsArray) {
        _buttonsArray = [NSMutableArray array];
    }
    
    return _buttonsArray;
}


#pragma mark - 通过传入的模型来设置HRTabBar的子控件
/** 当执行setItems: 方法时创建视图中的UIButton控件 */
- (void)setItems:(NSArray *)items {
    _items = items;
    
    // 根据items中的UITabBarItem的信息来创建
    for (NSInteger i = 0; i < items.count; ++i) {
        HRTabBarButton *button = [HRTabBarButton buttonWithType:UIButtonTypeCustom];
//        button.titleLabel.text = [items[i] title];
        [button setTitle:[items[i] title] forState:UIControlStateNormal];
        [button setImage:[items[i] image] forState:UIControlStateNormal];
        [button setImage:[items[i] selectedImage] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDown];
        button.index = i;
        
        [self addSubview:button];
        [self.buttonsArray addObject:button];
        
        if (i == 0) {
            button.selected = YES;
        }
    }
}

/** 重写方法，布局子控件 */
- (void)layoutSubviews {
    [super layoutSubviews];
    
//    if (self.buttonsArray.count == 0) return;
    
    CGFloat buttonW = self.bounds.size.width / self.items.count;
    CGFloat buttonH = self.bounds.size.height;
    
    for (NSInteger i = 0; i < self.items.count; ++i) {
        CGFloat buttonX = i * buttonW;
        CGFloat buttonY = 0;
        
        HRTabBarButton *button = self.buttonsArray[i];
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
    }
//    NSLog(@"%f, %f", buttonW, buttonH);
}

/** 当点击某个按钮时要执行的方法 */
- (void)tabBarButtonClick:(HRTabBarButton *)sender {
    // 如果点击的按钮已经是选中状态，那么就直接返回
    if (self.selectedButtonIndex == sender.index)
        return;
    
    // 否则取消已选中按钮的选中状态
    [self.buttonsArray[self.selectedButtonIndex] setSelected:NO];
    
    // 设置当前点击按钮状态为选中状态
    sender.selected = YES;
    
    // 记录选中的HRTabBarButton控件
    self.selectedItem = self.items[sender.index];
    self.selectedButtonIndex = sender.index;
    
    // 如果代理实现了协议方法，那么就让通过代理调用协议方法
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedAtIndex:)]) {
        [self.delegate tabBar:self didSelectedAtIndex:sender.index];
    }
}

@end
